package com.twxm.breed.iot;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.iot.model.v20180120.*;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.HashMap;
import java.util.List;

public class ALiYunIOTAPI {

    // ===================需要用户填写的参数开始===========================
    // 修改Config.*的参数为您的实际信息
    // 地域ID，根据您的物联网平台服务地域获取对应ID，https://help.aliyun.com/document_detail/40654.html
    private String regionId = "cn-shanghai";
    //qCH5fy58YlRWl0Py7X7ZoeT0boa99Q
    // 用户账号AccessKey ID
    private String accessKeyID = "LTAI5tCsHPN2T58pyYKiq9sF";
    // 用户账号AccesseKey Secret
    private String accessKeySecret = "qCH5fy58YlRWl0Py7X7ZoeT0boa99Q";
    // 要查询的设备所属的产品ProductKey
//    private static String productKey = "iumgPHecx5m";
//    // 要查询的设备名称deviceName
//    private static String deviceName = "ShuiBeng";
    private String IotInstanceId = "iot-06z00ed9mdyefid";
    // ===================需要用户填写的参数结束===========================
    private DefaultAcsClient client = null;

    private static ALiYunIOTAPI instance = null;
    public static ALiYunIOTAPI getInstance(){
        if(instance == null){
            instance = new ALiYunIOTAPI();
        }
        return instance;
    }

    public ALiYunIOTAPI(){
        try {
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyID, accessKeySecret);
            DefaultProfile.addEndpoint(regionId, regionId, "Iot", "iot." + regionId + ".aliyuncs.com");
            client = new DefaultAcsClient(profile);
        } catch (Exception e) {
            System.out.println("create Open API Client failed !! exception:" + e.getMessage());
        }
    }


    public boolean setDeviceOpen(String productKey, String deviceName) throws ClientException {
        JSONObject json = new JSONObject();
        json.put("Switch",1);
        return setDeviceProperty(productKey, deviceName, json);
    }

    public boolean setDeviceClose(String productKey,String deviceName) throws ClientException {
        JSONObject json = new JSONObject();
        json.put("Switch",0);
        return setDeviceProperty(productKey, deviceName, json);
    }
    /**
     * 查询单设备运行状态
     * GetDeviceStatus https://help.aliyun.com/document_detail/69617.html
     */
    public String getDeviceStatus(String productKey, String deviceName) throws ClientException {
        if(queryProperty(productKey, deviceName, "Switch").equals("1")){
            return "ONLINE";
        }return "OFFLINE";
    }

    // 查询设备属性数据，如温度，湿度等
    public String queryProperty(String productKey, String deviceName, String property) throws ClientException {
        QueryDevicePropertyDataRequest request = new QueryDevicePropertyDataRequest();

        request.setProductKey(productKey);// 目标设备产品key
        request.setIotInstanceId(IotInstanceId);
        request.setDeviceName(deviceName);// 目标设备名

        request.setIdentifier(property);

        long endTime = System.currentTimeMillis();
        long startTime = endTime - 1000 * 60 * 100;//1分钟数据
        //
        request.setStartTime(startTime);
        request.setEndTime(endTime);
        request.setAsc(0);
        request.setPageSize(10);

        QueryDevicePropertyDataResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            for (QueryDevicePropertyDataResponse.Data.PropertyInfo info:
                    response.getData().getList()){
                return info.getValue();
            }
        }else if(response != null){
            System.out.println("err:QueryProperty" + response.getCode() + ";" + response.getErrorMessage());
            return "";
        }else{
            System.out.println("no res");
            return "";
        }
        return "";
    }

    public boolean importDevice(String productKey,String deviceName) throws ClientException {
        RegisterDeviceRequest request = new RegisterDeviceRequest();

        request.setDeviceName(deviceName);
        request.setProductKey(productKey);
        request.setIotInstanceId(IotInstanceId);
        RegisterDeviceResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            // 成功添加
            System.out.println("importDeviceSuc");
            return true;
        }else if(response != null){
            System.out.println("err:"+"importDevice" + response.getCode() + ";" + response.getErrorMessage());
            throw new RuntimeException();
        }else{
            System.out.println("no res");
            throw new RuntimeException();
        }
    }

    public String createProduct(String productName) throws ClientException {
        CreateProductRequest request = new CreateProductRequest();

        request.setIotInstanceId(IotInstanceId);
        // 数据格式 1代表Alink协议（ALINK_FORMAT）
        request.setDataFormat(1);
        // 表示创建使用物模型的产品
        request.setAliyunCommodityCode("iothub_senior");
        request.setNodeType(0); // 设备

        request.setProductName(productName);
        CreateProductResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            // 成功添加
            response.getProductKey();
            System.out.println("createProductSuc");
            return response.getProductKey();
        }else if(response != null){
            System.out.println("err:" + "createProduct"+ response.getCode() + ";" +response.getErrorMessage());
            throw new RuntimeException();
        }else{
            System.out.println("no res");
            throw new RuntimeException();
        }
    }

    public boolean setDeviceProperty(String productKey,String deviceName,JSONObject jsonObject) throws ClientException {
        SetDevicePropertyRequest request = new SetDevicePropertyRequest();

        request.setDeviceName(deviceName);
        request.setProductKey(productKey);
        request.setIotInstanceId(IotInstanceId);

        request.setItems(jsonObject.toJSONString());
        SetDevicePropertyResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            // 成功输入数据
            return true;
        }else if(response != null){
            System.out.println("err:" + "setDeviceProperty;"+ response.getCode() + ";" +response.getErrorMessage());
            return false;
        }else{
            System.out.println("no res");
            return false;
        }

    }

    public HashMap<String, String> getProductAllProperty(String productKey) throws ClientException {
        QueryThingModelRequest request = new QueryThingModelRequest();

        request.setIotInstanceId(IotInstanceId);
        request.setProductKey(productKey);

        QueryThingModelResponse response = client.getAcsResponse(request);

        if(response != null && response.getSuccess()){
            // 成功输入数据
            System.out.println("getProductAllPropertySuc");
            String jsonStr = response.getData().getThingModelJson();
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            JSONArray properties = jsonObject.getJSONArray("properties");
            HashMap<String, String> propertiesMap = new HashMap<>();
            for (Object oProperty :
                    properties) {
                JSONObject property = (JSONObject) oProperty;
                String identifier = property.getString("identifier");
                String dataType = property.getString("dataType");
                propertiesMap.put(identifier, dataType);
            }
            return propertiesMap;
        }else if(response != null){
            System.out.println("err:" + "getProductAllProperty"+ response.getCode() + ";" +response.getErrorMessage());
        }else{
            System.out.println("no res");
        }
        return null;
    }


    public HashMap<String, String> queryProperties(String productKey, String deviceName, List<String> propertiesList) throws ClientException {
        QueryDevicePropertiesDataRequest request = new QueryDevicePropertiesDataRequest();
        request.setProductKey(productKey);// 目标设备产品key
        request.setIotInstanceId(IotInstanceId);
        request.setDeviceName(deviceName);// 目标设备名
        request.setIdentifiers(propertiesList);

        //long endTime = System.currentTimeMillis();
        //long startTime = endTime - 1000 * 60 * 2;//2分钟数据

        long startTime = System.currentTimeMillis();
        long endTime = startTime - 1000 * 60 * 60;//2分钟数据
//        request.setStartTime(startTime);
//        request.setEndTime(endTime);
        request.setStartTime(startTime);
        request.setEndTime(endTime);
        request.setAsc(0);
        request.setPageSize(10);

        HashMap<String, String> dataMap = new HashMap<>();

        QueryDevicePropertiesDataResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            List<QueryDevicePropertiesDataResponse.PropertyDataInfo> infos = response.getPropertyDataInfos();
            for (QueryDevicePropertiesDataResponse.PropertyDataInfo info : infos) {
                String name = info.getIdentifier();
                for (QueryDevicePropertiesDataResponse.PropertyDataInfo.PropertyInfo propertyInfo : info.getList()) {
                    dataMap.put(name,propertyInfo.getValue());
                    break;
                }

            }
        }else if(response != null){
            System.out.println("err:" +"QueryProperties"+ response.getCode() + ";" + response.getErrorMessage());
        }else{
            System.out.println("no res");
        }
        return dataMap;
    }

    public boolean deleteDevice(String productKey, String deviceName) throws ClientException {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setProductKey(productKey);// 目标设备产品key
        request.setIotInstanceId(IotInstanceId);
        request.setDeviceName(deviceName);// 目标设备名

        DeleteDeviceResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            System.out.println("delDeviceSuc");
            return true;
        }else if(response != null){
            System.out.println("err:" + "setDeviceProperty"+response.getErrorMessage());
            return false;
        }else{
            System.out.println("no res");
            return false;
        }
    }

    public void setDeviceDesiredProperty(String productKey,String deviceName,JSONObject jsonObject1,JSONObject jsonObject2) throws ClientException {
        SetDeviceDesiredPropertyRequest request = new SetDeviceDesiredPropertyRequest();

        request.setDeviceName(deviceName);
        request.setProductKey(productKey);
        request.setIotInstanceId(IotInstanceId);
        request.setItems(jsonObject1.toJSONString());
        request.setVersions(jsonObject2.toJSONString());

        SetDeviceDesiredPropertyResponse response = client.getAcsResponse(request);
        if(response != null && response.getSuccess()){
            // 成功输入数据
            System.out.println("setDeviceDesiredPropertySuc");
        }else if(response != null){
            System.out.println("err:" + "setDeviceDesiredProperty;"+ response.getCode() + ";" +response.getErrorMessage());
        }else{
            System.out.println("no res");
        }
    }
}